<?php
/**
 * 用户管理
 */

namespace backend\controllers;


use app\models\Admin;
use app\models\AdminGroup;
use app\models\AdminLog;
use yii;

class AdminController extends CommonController
{
    public function actionIndex()
    {
        $this->setQuery(Admin::find());
        return $this->query();
    }

    public function actionCreate()
    {
        $model = new Admin(['scenario' => 'create']);
        $group = AdminGroup::find()->select("id,name")->where(["status" => "1"])->all();
        $groupList = [];
        foreach ($group as $row) {
            $groupList[$row->id] = $row->name;
        }
        $this->setModel($model);
        $this->setParams(["groupList" => $groupList]);
        return $this->save();
    }

    public function actionUpdate($id)
    {
        $model = Admin::findOne($id);
        $model->setScenario("update");
        $group = AdminGroup::find()->select("id,name")->where(["status" => "1"])->all();
        $groupList = [];
        foreach ($group as $row) {
            $groupList[$row->id] = $row->name;
        }
        $this->setModel($model);
        $this->setParams(["groupList" => $groupList]);
        $this->setUrl(['index', 'page' => Yii::$app->request->get("page")]);
        return $this->save();
    }

    public function actionDelete()
    {
        $this->setModel(new Admin());
        $this->setUrl(['index', 'page' => Yii::$app->request->get('page')]);
        $this->delete();
    }

    public function actionGroupIndex()
    {
        $this->setQuery(AdminGroup::find());
        $this->setXView('group-index');
        return $this->query();
    }

    public function actionGroupCreate()
    {
        $model = new AdminGroup();
        if (Yii::$app->request->isPost) {
            $acl = array_unique((array)Yii::$app->request->post("acl"));
            $model->acl = implode(',', $acl);
        }
        $this->setModel($model);
        $this->setXView('group-form');
        $this->setUrl(['group-index']);
        return $this->save();
    }

    public function actionGroupUpdate($id)
    {
        $model = AdminGroup::findOne($id);
        if (Yii::$app->request->isPost) {
            $acl = array_unique((array)Yii::$app->request->post("acl"));
            $model->acl = implode(',', $acl);
        }
        $this->setModel($model);
        $this->setXView('group-form');
        $this->setUrl(['group-index', 'page' => Yii::$app->request->get("page")]);
        return $this->save();
    }

    public function actionGroupDelete()
    {
        $this->setModel(new AdminGroup());
        $this->setUrl(['group-index', 'page' => Yii::$app->request->get('page')]);
        $this->delete();
    }

    public function actionLogIndex()
    {
        $this->setQuery(AdminLog::find()->orderBy(['id' => SORT_DESC]));
        $this->setXView('log-index');
        return $this->query();
    }
}